﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using log4net;
using System.Data.SqlClient;
using Microsoft.Reporting.WebForms;

public partial class report : System.Web.UI.Page
{
     //Inject log4net
    private static readonly ILog logger = LogManager.GetLogger(typeof(report).Name);
    protected void Page_Load(object sender, EventArgs e)
    {
        RegisteringButton();
        
    }
    private void RegisteringButton()
    {
        //register javascript
        btnExport.Attributes.Add("onmouseover", "this.src='images/export_hover.jpg'");
        btnExport.Attributes.Add("onmouseout", "this.src='images/export.jpg'");
        btnExport.Visible = false;

        btnReset.Attributes.Add("onmouseover", "this.src='images/xoa_hover.gif'");
        btnReset.Attributes.Add("onmouseout", "this.src='images/xoa.gif'");

        btnSearch.Attributes.Add("onmouseover", "this.src='images/search_hover.gif'");
        btnSearch.Attributes.Add("onmouseout", "this.src='images/search.gif'");
    }


    #region SaleByInvoice Members  =========================================03============================================================
    /// <summary>
    /// 03
    /// </summary>
    private DataTable SaleByInvoice()
    {
        #region sql
        string strSQL = @"SELECT
	        T1.OrderNo
	        ,T1.OrderDate
	        ,COALESCE(QuantityOfCard,0) as QuantityOfCard
	        ,TotalPrice
	        ,Discount
	        ,CustomerName
        FROM
	        (SELECT
		        OrderNo
		        ,CONVERT(VARCHAR,OrderDate,103) AS OrderDate
		        ,TotalPrice
		        ,Discount
		        ,CustomerName
		        ,OrderID
	        FROM
		        [ORDER] O
		        ,Customer C
	        WHERE 
		        C.CustomerID=O.CustomerID
		        AND OrderDate >= @FromDate
		        AND OrderDate <= @ToDate
	        ) T1
        LEFT JOIN
	        (SELECT 
		        COUNT(ID) AS QuantityOfCard
		        ,OrderID
	        FROM
		        OrderDetail
		        GROUP BY  OrderID
	        )T2
        ON T1.OrderID=T2.OrderID"; 
        #endregion
        DataTable dt = null;         
            //parms
            SqlParameter[] parms = new SqlParameter[]{
                    new SqlParameter("@FromDate",DateTime.ParseExact(txtFrom.Text,Constants.DATE_PATTERN,null)),
                    new SqlParameter("@ToDate",DateTime.ParseExact(txtTo.Text,Constants.DATE_PATTERN,null))
                };
        try
        {
            dt= SqlHelper.ExecuteDataset(CommandType.Text, strSQL, parms).Tables[0];
            //save fromdate, todate to viewstate
            ViewState["FromDate"] = txtFrom.Text;
            ViewState["ToDate"] = txtTo.Text;
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
        }
        return dt;
    }
    private void ExportSaleByInvoice()
    {
        try
        {
            ViewState["FromDate"] = txtFrom.Text;
            ViewState["ToDate"] = txtTo.Text;
            ExportReport("SaveByInvoice", "AutoParkingDataSet_ViewTemp", (DataTable)ViewState["datasource"], Constants.REPORT_SAVE_BY_INVOICE);
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
        }
    }
    private void RepeaterSaleByInvoice()
    {
        DataTable dt = SaleByInvoice();
        if (dt.Rows.Count >0)
        {
            rptSaleByInvoice.DataSource = dt;
            rptSaleByInvoice.DataBind();
            //save dt to viewstate
            ViewState["datasource"] = dt;
            btnExport.Visible = true;
        }
        else {
            rptSaleByInvoice.Visible = false;
            msgResult.Text = Constants.NO_ITEM;
        }
    }
    #endregion  ========================================================================================================

    #region SaleParkingByDate Members ========================02=============================================================
    private DataTable SaleParkingByDate()
    {
        //parms
        SqlParameter[] parms = new SqlParameter[]{
                    new SqlParameter("@DateFrom",DateTime.ParseExact(txtFrom.Text,Constants.DATE_PATTERN,null)),
                    new SqlParameter("@DateTo",DateTime.ParseExact(txtTo.Text,Constants.DATE_PATTERN,null))
                };
        DataTable dt=null;
        try
        {
            dt = SqlHelper.ExecuteDataset(CommandType.StoredProcedure, "[dbo].[usp_DailySaleReport]", parms).Tables[0];
            //save fromdate, todate to viewstate
            ViewState["FromDate"] = txtFrom.Text;
            ViewState["ToDate"] = txtTo.Text;
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
        }
        return dt;
    }

    private void ExportSaleParkingByDate()
    {
        try
        {
            ViewState["FromDate"] = txtFrom.Text;
            ViewState["ToDate"] = txtTo.Text;
            ExportReport("SaLeParkingByDate", "DailySaleDataSet_temp", (DataTable)ViewState["datasource"], Constants.REPORT_SALE_PARKING_BY_DATE);
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
        }
    }
   

    private void RepeaterSaleParkingByDate() {
        DataTable dt = SaleParkingByDate();
        if (dt != null)
        {
            rptSaveParkingByDate.DataSource = dt;
            rptSaveParkingByDate.DataBind();
            //save dt to viewstate
            ViewState["datasource"] = dt;
            btnExport.Visible = true;
        }
        else { 
        
        }
    }
    
    #endregion

    #region SaleCardByDate Members ========================1st Report=============================================================

    private void ExportSaleCardByDate()
    {
        try
        {
            ViewState["FromDate"] = txtFrom.Text;
            ViewState["ToDate"] = txtTo.Text;
            ExportReport("SaveCardByDate", "SaleCardByDateDataSet_viewTepm2", (DataTable)ViewState["datasource"], Constants.REPORT_SALE_CARD_BY_DATE);
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
        }
    }
    private void RepeaterSaleCardByDate()
    {
        DataTable dt = SaleCardByDate();
        if (dt.Rows.Count > 0)
        {
            rptSaleCardByDate.DataSource = dt;
            rptSaleCardByDate.DataBind();
            //save dt to viewstate
            ViewState["datasource"] = dt;
            btnExport.Visible = true;
            msgResult.Text = "";
        }
        else
        {
            rptSaleCardByDate.Visible = false;
            msgResult.Text = Constants.NO_ITEM;
        }
    }


    /// <summary>
    /// 03
    /// </summary>
    private DataTable SaleCardByDate()
    {
        #region sql
        string strSQL = @"SELECT
	                        CONVERT(VARCHAR,OrderDate,103) AS OrderDate
	                        ,SUm(TotalPrice) AS TotalPrice
                        FROM
	                        [ORDER]
                        WHERE 
	                        OrderDate >= @FromDate
	                        AND OrderDate <= @ToDate
                        GROUP BY OrderDate";
        #endregion

        //parms
        SqlParameter[] parms = new SqlParameter[]{
                    new SqlParameter("@FromDate",DateTime.ParseExact(txtFrom.Text,Constants.DATE_PATTERN,null)),
                    new SqlParameter("@ToDate",DateTime.ParseExact(txtTo.Text,Constants.DATE_PATTERN,null))
                };
        DataTable dt = null;
        try
        {
           dt = SqlHelper.ExecuteDataset(CommandType.Text, strSQL, parms).Tables[0];
            //save fromdate, todate to viewstate
            ViewState["FromDate"] = txtFrom.Text;
            ViewState["ToDate"] = txtTo.Text;
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
        }
        return dt;
    }


    #endregion

    #region MonthCardByCustomer Members ========================04 Report=============================================================

    private void ExportMonthCardByCustomer()
    {
        try
        {
            ViewState["FromDate"] = txtFrom.Text;
            ViewState["ToDate"] = txtTo.Text;
            ExportReport("MonthCardByCustomer", "AutoParkingDataSet_vw_MontCardByCustomer", (DataTable)ViewState["datasource"], Constants.REPORT_MONTH_CARD_BY_CUSTOMER);
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
        }
    }
    private void RepeaterMonthCardByCustomer()
    {
        DataTable dt = MonthCardByCustomer();
        if (dt.Rows.Count > 0)
        {
            rptMonthCardByCustomer.DataSource = dt;
            rptMonthCardByCustomer.DataBind();
            //save dt to viewstate
            ViewState["datasource"] = dt;
            btnExport.Visible = true;
            msgResult.Text = "";
        }
        else
        {
            rptMonthCardByCustomer.Visible = false;
            msgResult.Text = Constants.NO_ITEM;
        }
    }


    /// <summary>
    /// 04
    /// </summary>
    private DataTable MonthCardByCustomer()
    {
        string sql = @"SELECT CurrentDate,FullName,BuyDate,NoOfTime,Total 
                    FROM ufn_DateList(@DateFrom, @DateTo)
                    LEFT JOIN
	                    (SELECT 
		                    FullName
		                    ,CONVERT(VARCHAR(10),CreateDate,103) BuyDate 
		                    ,COUNT(Id) as NoOfTime
		                    ,SUM(COALESCE(Price,0)) AS Total
	                    FROM
		                    MonthCard
	                    GROUP BY FullName,CONVERT(VARCHAR(10),CreateDate,103)
	                    )M ON CurrentDate =M.BuyDate";
        //parms
        SqlParameter[] parms = new SqlParameter[]{
                    new SqlParameter("@DateFrom",DateTime.ParseExact(txtFrom.Text,Constants.DATE_PATTERN,null)),
                    new SqlParameter("@DateTo",DateTime.ParseExact(txtTo.Text,Constants.DATE_PATTERN,null))
                };
        DataTable dt = new DataTable();
        try
        {
            dt = SqlHelper.ExecuteDataset(CommandType.Text, sql, parms).Tables[0];
            //save fromdate, todate to viewstate
            ViewState["FromDate"] = txtFrom.Text;
            ViewState["ToDate"] = txtTo.Text;
        }
        catch (Exception ex)
        {
            lblMsg.Text = Constants.ERROR_MSG;
            if (logger.IsErrorEnabled) { logger.Error(ex.Message); }
        }
        return dt;
    }


    #endregion

























    #region Utils
    private void ExportReport(string fileName, string dataSourceName, DataTable dataSource, string rdlcFile)
    {
        
        try
        {
            //Check viewstate
            if (ViewState["FromDate"] == null)
                return;
            if (ViewState["ToDate"] == null)
                return;
            string from = ViewState["FromDate"].ToString();
            string to = ViewState["ToDate"].ToString();

            LocalReport localReport = new LocalReport();
            localReport.ReportPath = HttpContext.Current.Server.MapPath(Constants.REPORT_PATH + rdlcFile);

            //params
            ReportParameter fromDate = new ReportParameter("FromDate", from);
            ReportParameter toDate = new ReportParameter("ToDate", to);
            localReport.SetParameters(new ReportParameter[] { fromDate, toDate});

            ReportDataSource reportDataSource = new ReportDataSource(dataSourceName, dataSource);
            //Clear datasource
            localReport.DataSources.Clear();
            localReport.DataSources.Add(reportDataSource);

            string reportType = "PDF";
            string mimeType;
            string encoding;
            string fileNameExtension;
            string deviceInfo =
            

            "<DeviceInfo>" +
            "  <OutputFormat>PDF</OutputFormat>" +
            "  <MarginTop>0.3in</MarginTop>";
            if (rdlcFile.Equals(Constants.REPORT_SALE_CARD_BY_DATE))
            {
                deviceInfo += "  <MarginLeft>2.5in</MarginLeft>" +
                                "  <PageWidth>8.5in</PageWidth>" +
                                 "  <PageHeight>11in</PageHeight>";
            }
            else if (rdlcFile.Equals(Constants.REPORT_SAVE_BY_INVOICE))
            {
                deviceInfo += "  <MarginLeft>0.5in</MarginLeft>" +
                               "  <PageWidth>11in</PageWidth>" +
                                "  <PageHeight>8.5in</PageHeight>";
            }
            else if (rdlcFile.Equals(Constants.REPORT_MONTH_CARD_BY_CUSTOMER))
            {
                deviceInfo += "  <MarginLeft>0.7in</MarginLeft>" +
                               "  <PageWidth>11in</PageWidth>" +
                                "  <PageHeight>8.5in</PageHeight>";
            }
            else
            {

                deviceInfo += "  <MarginLeft>0.85in</MarginLeft>" +
                                "  <PageWidth>8.5in</PageWidth>" +
                                 "  <PageHeight>11in</PageHeight>";
            }
            deviceInfo +=
            "  <MarginRight>0.5in</MarginRight>" +
            "  <MarginBottom>0.1in</MarginBottom>" +
            "</DeviceInfo>";

            Warning[] warnings;
            string[] streams;
            byte[] renderedBytes;

            //Render the report
            renderedBytes = localReport.Render(reportType,
                                                deviceInfo,
                                                out mimeType,
                                                out encoding,
                                                out fileNameExtension,
                                                out streams,
                                                out warnings);
            //Clear the response stream and write the bytes to the outputstream
            //Set content-disposition to "attachment" so that user is prompted to take an action
            //on the file (open or save)
            Response.Clear();
            Response.ContentType = mimeType;
            Response.AddHeader("content-disposition", "attachment; filename=" + fileName + "." + fileNameExtension);
            Response.BinaryWrite(renderedBytes);
            //Response.End();
            Response.Flush();
            Response.Close();
        }
        catch (Exception)
        {
            throw;
        }
    } 
    #endregion



    #region Events
    protected void btnReset_Click(object sender, ImageClickEventArgs e)
    {
        ddlReport.SelectedValue = "";
        txtFrom.Text = "";
        txtTo.Text = "";
    }


    protected void btnSearch_Click(object sender, ImageClickEventArgs e)
    {
        string strRepeater = ddlReport.SelectedValue;
        switch (strRepeater)
        {
            case "01":
                RepeaterSaleCardByDate();
                break;
            case "02":
                RepeaterSaleParkingByDate();
                break;
            case "03":
                RepeaterSaleByInvoice();
                break;
            case "04":
                RepeaterMonthCardByCustomer();
                break;
            default:
                break;
        }
    }
    protected void rptSaveParkingByDate_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        //Content
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Label lblTotal = (Label)e.Item.FindControl("lblTotal");
            Label lblNormalPrice = (Label)e.Item.FindControl("lblNormalPrice");
            Label lblMonthPrice = (Label)e.Item.FindControl("lblMonthPrice");
            lblTotal.Text = (Double.Parse(lblMonthPrice.Text.ToString()) + Double.Parse(lblNormalPrice.Text.ToString())).ToString();
        }
    }


    protected void btnExport_Click(object sender, ImageClickEventArgs e)
    {
        string strReport = ddlReport.SelectedValue;
        switch (strReport)
        {
            case "01":
                ExportSaleCardByDate();
                break;
            case "02":
                ExportSaleParkingByDate();
                break;
            case "03":
                ExportSaleByInvoice();
                break;
            case "04":
                ExportMonthCardByCustomer();
                break;
            default:
                break;
        }
    }
    protected void rptSaleByInvoice_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        //Content
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Label lblTotalPrice = (Label)e.Item.FindControl("lblTotalPrice");
            Label lblDiscount = (Label)e.Item.FindControl("lblDiscount");
            Label lblPrac = (Label)e.Item.FindControl("lblPrac");
            Double total = Double.Parse(lblTotalPrice.Text);
            Double discount = Double.Parse(lblDiscount.Text);
            lblPrac.Text = (total - (total * discount / 100)).ToString();
        }
    }

    protected void rptMonthCardByCustomer_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        //Content
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Label total = (Label)e.Item.FindControl("lblTotal");
            if (!string.IsNullOrEmpty(total.Text.Trim()))
                total.Text = Double.Parse(total.Text.Trim()).ToString("0,0.00");
        }
        
    } 
    #endregion
   
}
